import React, { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Folder, Star, Shield, Crown, Award, Users, Filter, X } from 'lucide-react';
import { avatarApi } from '../api';
import type { AvatarGroup } from '../api/types';
import { useApiError } from '../hooks/useApiError';

const Avatars: React.FC = () => {
  const navigate = useNavigate();
  const { handleError } = useApiError();
  const [groups, setGroups] = useState<AvatarGroup[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [activeTab, setActiveTab] = useState<'my_groups' | 'public_groups'>('my_groups');
  const [selectedFilters, setSelectedFilters] = useState<string[]>([]);
  const [showFilters, setShowFilters] = useState(false);

  const loadAvatarGroups = useCallback(async () => {
    try {
      setLoading(true);

      // 使用简化的API - 直接返回data字段
      const data = await avatarApi.getGroups({ include_public: true, limit: 100 });

      console.log('Avatar Groups Data:', data);

      // 使用新的统一列表响应格式
      const groupList = data?.rows || [];
      setGroups(groupList);
    } catch (error) {
      handleError(error, '加载Avatar组失败');
    } finally {
      setLoading(false);
    }
  }, [handleError]);

  useEffect(() => {
    loadAvatarGroups();
  }, [loadAvatarGroups]);

  // 切换标签页时清除过滤器
  useEffect(() => {
    setSelectedFilters([]);
    setSearchTerm('');
  }, [activeTab]);

  // 根据 group_type 分类组
  const getMyGroups = () => {
    return groups.filter(group => group.group_type === 'PRIVATE' || group.group_type === 'PHOTO');
  };

  const getPublicGroups = () => {
    return groups.filter(
      group =>
        group.group_type === 'PUBLIC' ||
        group.group_type === 'PUBLIC_PHOTO' ||
        group.group_type === 'COMMUNITY_PHOTO'
    );
  };

  // 获取可用的过滤器选项（基于当前标签页）
  const getAvailableFilterOptions = () => {
    if (activeTab === 'my_groups') {
      return [
        { value: 'PRIVATE', label: '私有组', icon: Shield, color: 'blue' },
        { value: 'PHOTO', label: '照片组', icon: Users, color: 'purple' },
      ];
    } else {
      return [
        { value: 'PUBLIC', label: '公共组', icon: Crown, color: 'green' },
        { value: 'PUBLIC_PHOTO', label: '公共照片', icon: Award, color: 'yellow' },
        { value: 'COMMUNITY_PHOTO', label: '社区照片', icon: Star, color: 'pink' },
      ];
    }
  };

  // 处理过滤器选择
  const handleFilterToggle = (filterValue: string) => {
    setSelectedFilters(prev =>
      prev.includes(filterValue) ? prev.filter(f => f !== filterValue) : [...prev, filterValue]
    );
  };

  // 清除所有过滤器
  const clearAllFilters = () => {
    setSelectedFilters([]);
    setSearchTerm('');
  };

  // 应用搜索和类型过滤
  const getFilteredGroups = () => {
    const sourceGroups = activeTab === 'my_groups' ? getMyGroups() : getPublicGroups();

    let filtered = sourceGroups;

    // 应用类型过滤
    if (selectedFilters.length > 0) {
      filtered = filtered.filter(group => selectedFilters.includes(group.group_type));
    }

    // 应用搜索过滤
    if (searchTerm) {
      filtered = filtered.filter(group =>
        group.name.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    return filtered;
  };

  const filteredGroups = getFilteredGroups();
  const myGroupsCount = getMyGroups().length;
  const publicGroupsCount = getPublicGroups().length;

  // 获取组类型图标
  const getGroupTypeIcon = (type: string) => {
    switch (type) {
      case 'PRIVATE':
        return <Shield className="w-4 h-4 text-blue-400" />;
      case 'PHOTO':
        return <Users className="w-4 h-4 text-purple-400" />;
      case 'PUBLIC':
        return <Crown className="w-4 h-4 text-green-400" />;
      case 'PUBLIC_PHOTO':
        return <Award className="w-4 h-4 text-yellow-400" />;
      case 'COMMUNITY_PHOTO':
        return <Star className="w-4 h-4 text-pink-400" />;
      default:
        return <Folder className="w-4 h-4 text-gray-400" />;
    }
  };

  // 获取组类型显示名称
  const getGroupTypeLabel = (type: string) => {
    switch (type) {
      case 'PRIVATE':
        return '私有组';
      case 'PHOTO':
        return '照片组';
      case 'PUBLIC':
        return '公共组';
      case 'PUBLIC_PHOTO':
        return '公共照片';
      case 'COMMUNITY_PHOTO':
        return '社区照片';
      default:
        return type;
    }
  };

  return (
    <div>
      <div className="mb-8">
        <h2 className="text-3xl font-bold text-gray-100 mb-2">Avatar Groups</h2>
        <p className="text-gray-400">管理和浏览 Avatar 组，点击进入组查看其中的 Avatars</p>
      </div>

      {/* Tabs */}
      <div className="flex space-x-1 mb-6 bg-gray-900 p-1 rounded-lg w-fit">
        <button
          onClick={() => setActiveTab('my_groups')}
          className={`px-4 py-2 rounded-md font-medium transition-all flex items-center space-x-2 cursor-pointer ${
            activeTab === 'my_groups'
              ? 'bg-gradient-to-r from-cyan-500 to-blue-500 text-white'
              : 'text-gray-400 hover:text-gray-200'
          }`}
        >
          <Shield className="w-4 h-4" />
          <span>我的组 ({myGroupsCount})</span>
        </button>
        <button
          onClick={() => setActiveTab('public_groups')}
          className={`px-4 py-2 rounded-md font-medium transition-all flex items-center space-x-2 cursor-pointer ${
            activeTab === 'public_groups'
              ? 'bg-gradient-to-r from-cyan-500 to-blue-500 text-white'
              : 'text-gray-400 hover:text-gray-200'
          }`}
        >
          <Crown className="w-4 h-4" />
          <span>公共组 ({publicGroupsCount})</span>
        </button>
      </div>

      {/* Search and Filters */}
      <div className="flex flex-col md:flex-row gap-4 mb-6">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-500" />
          <input
            type="text"
            placeholder={activeTab === 'my_groups' ? '搜索我的组...' : '搜索公共组...'}
            value={searchTerm}
            onChange={e => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-3 bg-gray-900 border border-gray-800 rounded-lg text-gray-100 placeholder-gray-500 focus:outline-none focus:border-cyan-500 transition-colors"
          />
        </div>

        {/* Filter Toggle Button */}
        <button
          onClick={() => setShowFilters(!showFilters)}
          className={`flex items-center space-x-2 px-4 py-3 border rounded-lg transition-colors cursor-pointer ${
            showFilters || selectedFilters.length > 0
              ? 'bg-cyan-500/10 border-cyan-500/50 text-cyan-400'
              : 'bg-gray-900 border-gray-800 text-gray-400 hover:text-gray-200 hover:border-gray-700'
          }`}
        >
          <Filter className="w-5 h-5" />
          <span>过滤器</span>
          {selectedFilters.length > 0 && (
            <span className="bg-cyan-500 text-white text-xs px-2 py-1 rounded-full">
              {selectedFilters.length}
            </span>
          )}
        </button>

        {/* Clear Filters Button */}
        {(selectedFilters.length > 0 || searchTerm) && (
          <button
            onClick={clearAllFilters}
            className="flex items-center space-x-2 px-4 py-3 bg-red-500/10 border border-red-500/50 text-red-400 rounded-lg hover:bg-red-500/20 transition-colors cursor-pointer"
          >
            <X className="w-5 h-5" />
            <span>清除</span>
          </button>
        )}
      </div>

      {/* Filter Options */}
      {showFilters && (
        <div className="mb-6 p-4 bg-gray-900 border border-gray-800 rounded-lg">
          <h3 className="text-sm font-medium text-gray-300 mb-3">按类型过滤</h3>
          <div className="flex flex-wrap gap-3">
            {getAvailableFilterOptions().map(option => {
              const IconComponent = option.icon;
              const isSelected = selectedFilters.includes(option.value);

              return (
                <label
                  key={option.value}
                  className={`flex items-center space-x-2 px-3 py-2 rounded-lg border cursor-pointer transition-colors ${
                    isSelected
                      ? option.color === 'blue'
                        ? 'bg-blue-500/10 border-blue-500/50 text-blue-400'
                        : option.color === 'purple'
                          ? 'bg-purple-500/10 border-purple-500/50 text-purple-400'
                          : option.color === 'green'
                            ? 'bg-green-500/10 border-green-500/50 text-green-400'
                            : option.color === 'yellow'
                              ? 'bg-yellow-500/10 border-yellow-500/50 text-yellow-400'
                              : option.color === 'pink'
                                ? 'bg-pink-500/10 border-pink-500/50 text-pink-400'
                                : 'bg-cyan-500/10 border-cyan-500/50 text-cyan-400'
                      : 'bg-gray-800 border-gray-700 text-gray-400 hover:text-gray-200 hover:border-gray-600'
                  }`}
                >
                  <input
                    type="checkbox"
                    checked={isSelected}
                    onChange={() => handleFilterToggle(option.value)}
                    className="sr-only"
                  />
                  <IconComponent className="w-4 h-4" />
                  <span className="text-sm">{option.label}</span>
                </label>
              );
            })}
          </div>
        </div>
      )}

      {/* Content */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-500"></div>
        </div>
      ) : filteredGroups.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-64 text-gray-400">
          <Folder className="w-16 h-16 mb-4 opacity-50" />
          <p className="text-lg font-medium">暂无数据</p>
          <p className="text-sm mt-2 text-center">
            {searchTerm || selectedFilters.length > 0 ? (
              <>
                没有找到匹配的Avatar组
                <br />
                <span className="text-xs">尝试调整搜索条件或过滤器</span>
              </>
            ) : activeTab === 'my_groups' ? (
              '您还没有创建任何Avatar组'
            ) : (
              '暂无可用的公共组'
            )}
          </p>
          {(searchTerm || selectedFilters.length > 0) && (
            <button
              onClick={clearAllFilters}
              className="mt-4 px-4 py-2 bg-cyan-500/10 border border-cyan-500/50 text-cyan-400 rounded-lg hover:bg-cyan-500/20 transition-colors text-sm cursor-pointer"
            >
              清除所有过滤条件
            </button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredGroups.map(group => (
            <div
              key={group.group_id}
              className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden hover:border-cyan-500/50 transition-all group cursor-pointer"
              onClick={() => navigate(`/avatars/group/${group.group_id}`)}
            >
              <div className="relative aspect-square">
                <img
                  src={group.preview_image}
                  alt={group.name}
                  className="w-full h-full object-cover"
                />

                {/* 组类型标识 */}
                <div className="absolute top-2 left-2 bg-black/50 backdrop-blur-sm px-2 py-1 rounded-full flex items-center space-x-1">
                  {getGroupTypeIcon(group.group_type)}
                  <span className="text-xs text-white font-medium">
                    {getGroupTypeLabel(group.group_type)}
                  </span>
                </div>

                {/* 训练状态 */}
                {group.train_status && (
                  <div className="absolute top-2 right-2 bg-black/50 backdrop-blur-sm px-2 py-1 rounded-full">
                    <span
                      className={`text-xs font-medium ${
                        group.train_status === 'ready'
                          ? 'text-green-400'
                          : group.train_status === 'training'
                            ? 'text-yellow-400'
                            : 'text-gray-400'
                      }`}
                    >
                      {group.train_status === 'ready'
                        ? '已训练'
                        : group.train_status === 'training'
                          ? '训练中'
                          : group.train_status}
                    </span>
                  </div>
                )}

                <div className="absolute bottom-2 left-2 bg-black/50 backdrop-blur-sm px-2 py-1 rounded-full">
                  <span className="text-xs text-white font-medium">{group.num_looks} avatars</span>
                </div>

                {/* 悬停操作按钮 */}
                <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end justify-center pb-4">
                  <button className="bg-cyan-500 hover:bg-cyan-600 text-white px-4 py-2 rounded-lg flex items-center space-x-2 transition-colors text-sm cursor-pointer">
                    <Folder className="w-4 h-4" />
                    <span>查看 Avatars</span>
                  </button>
                </div>
              </div>

              <div className="p-4">
                <h3 className="font-semibold text-gray-100 mb-1">{group.name}</h3>
                <p className="text-sm text-gray-400">{group.num_looks} avatars</p>

                {/* 组类型标签 */}
                <div className="mt-2">
                  <span
                    className={`inline-block px-2 py-1 rounded-full text-xs border flex items-center space-x-1 w-fit ${
                      group.group_type === 'PRIVATE'
                        ? 'bg-blue-500/10 text-blue-400 border-blue-500/20'
                        : group.group_type === 'PHOTO'
                          ? 'bg-purple-500/10 text-purple-400 border-purple-500/20'
                          : group.group_type === 'PUBLIC'
                            ? 'bg-green-500/10 text-green-400 border-green-500/20'
                            : group.group_type === 'PUBLIC_PHOTO'
                              ? 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'
                              : group.group_type === 'COMMUNITY_PHOTO'
                                ? 'bg-pink-500/10 text-pink-400 border-pink-500/20'
                                : 'bg-gray-500/10 text-gray-400 border-gray-500/20'
                    }`}
                  >
                    {getGroupTypeIcon(group.group_type)}
                    <span>{getGroupTypeLabel(group.group_type)}</span>
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default Avatars;
